package com.iptv.grape.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DevInfoManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;

import com.iptv.grape.RunTimeApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

public class SystemUtil {
    /**
     * 固件版本
     * @return
     */
    public static String getFirmware() {
        String curSTBROMVersion = "";
        if (Glober.curHard.equals(Glober.HARD_ZTE)) {
            curSTBROMVersion = sysGet("ro.product.version.software");
        } else if (Glober.curHard.equals(Glober.HARD_HUAWEI)) {
            // curSTBROMVersion =
            // SystemProperties.get("ro.build.version.incremental");
        } else if (Glober.curHard.equals(Glober.HARD_Fiberhome)
                || Glober.curHard.equals(Glober.HARD_Skyworth)
                || Glober.curHard.equals(Glober.HARD_Hisense)
                || Glober.curHard.equals(Glober.HARD_Inspur)
                || Glober.curHard.equals(Glober.HARD_BesTV)
                || Glober.curHard.equals(Glober.HARD_BeiEr)) {
            curSTBROMVersion = sysGet("ro.build.version.incremental");
            AppLog.getCurLog().e("=======>进入"+curSTBROMVersion);
        }
        return curSTBROMVersion;
    }

    public static String sysGet(String property) {
        try {
            Class clazz = Class.forName("android.os.SystemProperties");
            Method getter = clazz.getDeclaredMethod("get", String.class);//方法名，参数类型
            String value = (String) getter.invoke(clazz.newInstance(), property);
            if (!TextUtils.isEmpty(value)) {
                return value;
            }
        } catch (Exception e) {
            AppLog.getCurLog().d("Unable to read system properties");
        }
        return "";
    }

    /**
     * getUsername(获取电信电视itv账号)
     * @return String 返回类型
     * @modifyHistory createBy baijie
     */
    public static String getIptvAccount() {
        String value = "";
        try {
            if (Glober.curHard.equals(Glober.HARD_ZTE)) {
                @SuppressLint("WrongConstant")
                DevInfoManager mDevInfoMgr = (DevInfoManager) RunTimeApplication.getCurApp().getSystemService(DevInfoManager.DATA_SERVER);
                value = mDevInfoMgr.getValue("Account");
                AppLog.getCurLog().e("中兴账号：" + value);
            } else if (Glober.curHard.equals(Glober.HARD_Fiberhome) || Glober.curHard.equals(Glober.HARD_HUAWEI) || Glober.curHard.equals(Glober.HARD_Hisense) || Glober.curHard.equals(Glober.HARD_RuiSiKangDa) || Glober.curHard.equals(Glober.HARD_Skyworth)) {
                Uri uri = Uri.parse("content://stbconfig/authentication");
                Cursor mCursor = RunTimeApplication.getCurApp().getApplicationContext().getContentResolver().query(uri, null, null, null, null);
                if (mCursor != null) {
                    while (mCursor.moveToNext()) {
                        String name = mCursor.getString(mCursor.getColumnIndex("name"));
                        if (name.equals("username")) {
                            value = mCursor.getString(mCursor.getColumnIndex("value"));
                            break;
                        }
                    }
                    mCursor.close();
                } else {
                    return "";
                }
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
            AppLog.getCurLog().out(ex.getMessage());
        }
        return value.trim();
    }




    public static String getMac() {
        String mac = "02:00:00:00:00:00";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mac = getMacDefault();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mac = getMacFromFile();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mac = getMacFromHardware();
        }
        mac = mac.replace(":","");
        return mac;
    }


    public static  String getMacAddress(){
        String strMacAddr = null;
        try {
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip)
                    .getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i]&0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String mac = getMac();
        return strMacAddr;
    }

    /**
     * 获取移动设备本地IP
     * @return
     */
    private static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            //列举
            Enumeration en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {//是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一个元素
                Enumeration en_ip = ni.getInetAddresses();//得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = (InetAddress) en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }
                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ip;
    }




    /**
     * Android  6.0 之前（不包括6.0）
     * 必须的权限  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     * @return
     */
    private static String getMacDefault( ) {
        String mac = "02:00:00:00:00:00";
        if (RunTimeApplication.getCurApp() == null) {
            return mac;
        }

        WifiManager wifi = (WifiManager) RunTimeApplication.getCurApp().getApplicationContext()
                .getSystemService(RunTimeApplication.getCurApp().WIFI_SERVICE);
        if (wifi == null) {
            return mac;
        }
        WifiInfo info = null;
        try {
            info = wifi.getConnectionInfo();
        } catch (Exception e) {
        }
        if (info == null) {
            return null;
        }
        mac = info.getMacAddress();
        if (!TextUtils.isEmpty(mac)) {
            mac = mac.toUpperCase(Locale.ENGLISH);
        }
        return mac;
    }
    /**
     * Android 6.0（包括） - Android 7.0（不包括）
     * @return
     */
    private static String getMacFromFile() {
        String WifiAddress = "02:00:00:00:00:00";
        try {
            WifiAddress = new BufferedReader(new FileReader(new File("/sys/class/net/wlan0/address"))).readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return WifiAddress;
    }
    /**
     * 遍历循环所有的网络接口，找到接口是 wlan0
     * 必须的权限 <uses-permission android:name="android.permission.INTERNET" />
     * @return
     */
    private static String getMacFromHardware() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "02:00:00:00:00:00";
    }





    /**
     * 获取当前ip地址
     *
     * @return
     */
    public static String getIp() {
        try {
            WifiManager wifiManager = (WifiManager) RunTimeApplication.getCurApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int i = wifiInfo.getIpAddress();
            return int2ip(i);
        } catch (Exception ex) {
            return " 获取IP出错鸟!!!!请保证是WIFI,或者请重新打开网络!\n" + ex.getMessage();
        }
        // return null;
    }
    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    private static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }


    //    网络设置
    public static void startNetSet(Activity activity)
    {
        Intent intent = new Intent();
        if (Glober.curHard.equals(Glober.HARD_ZTE))
        {
            ComponentName componentName = new ComponentName("com.android.settings", "com.android.settings.Settings");
            intent.setAction("android.settings.SETTINGS");
            intent.setAction("android.intent.action.VIEW");
            intent.setComponent(componentName);

        } else if (Glober.curHard.equals(Glober.HARD_HUAWEI))
        {
            ComponentName componentName = new ComponentName("com.android.settings", "com.android.settings.c10.NetWorkActivity2");
            intent.setAction("android.settings.NETWORK_SETTINGS");
            intent.setAction("android.intent.action.VIEW");
            intent.setComponent(componentName);
        } else if (Glober.curHard.equals(Glober.HARD_Fiberhome))
        {
            ComponentName componentName = new ComponentName("com.android.settings", "com.android.settings.fh.NetWorkActivity");
            intent.setAction("com.android.settings");
            intent.setAction("android.intent.action.VIEW");
            intent.setComponent(componentName);
        } else if (Glober.curHard.equals(Glober.HARD_Skyworth))
        {
            ComponentName componentName = new ComponentName("com.skyworth.sksettingsbootguide", "com.skyworth.sksettingsbootguide.MainActivity");
            intent.setAction("com.skyworth.sksettingsbootguide");
            intent.setAction("android.intent.action.VIEW");
            intent.setComponent(componentName);
        } else if (Glober.curHard.equals(Glober.HARD_Hisense))
        {
            ComponentName componentName = new ComponentName("com.android.settings", "com.android.settings.SettingsActivity");
            intent.setAction("com.android.settings");
            intent.setAction("android.intent.action.VIEW");
            intent.setComponent(componentName);
        } else if (Glober.curHard.equals(Glober.HARD_BesTV))
        {
            ComponentName componentName = new ComponentName("com.android.smart.terminal.settings", "com.android.smart.terminal.settings.LaunchActivity");
            intent.setAction("com.android.smart.terminal.settings");
            intent.setAction("android.intent.action.VIEW");
            intent.setComponent(componentName);
        } else if (Glober.curHard.equals(Glober.HARD_BeiEr))
        {
            ComponentName componentName = new ComponentName("com.android.smart.terminal.settings", "com.android.smart.terminal.settings.LaunchActivity");
            intent.setAction("com.android.smart.terminal.settings");
            intent.setAction("android.intent.action.VIEW");
            intent.setComponent(componentName);
        }
        // else if(Glober.curHard.equals(Glober.HARD_XiangShang))
        // {
        // intent = new Intent("android.settings.SETTINGS");
        // activity.startActivity(intent);
        // return;
        // }
        else
        {
            return;
        }
        activity.startActivityForResult(intent, 400);
    }
    /***
     * 支撑运营商代码
     * @return
     */
    public static String getOperator(){
        return sysGet("ro.build.operator");
    }

    /***
     * 硬件厂商名称
     * @return
     */
    public static String getHard(){
        return sysGet("ro.build.hard");
    }

    /***
     * 设备型号
     * @return
     */
    public static String getEquipment(){
        return sysGet("ro.build.equipment");
    }

    /**
     * 操作系统版本
     * @return
     */
    public static String getAndroid(){
        return sysGet("ro.build.android");
    }

    /**
     * 牌照方厂家
     * @return
     */
    public static String getLicence(){
        return sysGet("ro.build.licence");
    }

    /***
     * CDN厂家
     * @return
     */
    public static String getCdn(){
        return sysGet("ro.build.cdn");
    }


    public static String getMacAddress2() {
        String mac=null;
        try {
            Enumeration localEnumeration=NetworkInterface.getNetworkInterfaces();

            while (localEnumeration.hasMoreElements()) {
                NetworkInterface localNetworkInterface=(NetworkInterface) localEnumeration.nextElement();
                String interfaceName=localNetworkInterface.getDisplayName();

                if (interfaceName==null) {
                    continue;
                }

                if (interfaceName.equals("eth0")) {
                    // MACAddr = convertMac(localNetworkInterface
                    // .getHardwareAddress());
                    mac=convertToMac(localNetworkInterface.getHardwareAddress());
                    if (mac!=null&&mac.startsWith("0:")) {
                        mac="0"+mac;
                    }
                    break;
                }

                // byte[] address =
                // localNetworkInterface.getHardwareAddress();
                // Log.i(TAG, "mac=" + address.toString());
                // for (int i = 0; (address != null && i < address.length);
                // i++)
                // {
                // Log.i("Debug", String.format("  : %x", address[i]));
                // }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return mac;
    }

    private static String convertToMac(byte[] mac) {
        StringBuilder sb=new StringBuilder();
        for (int i=0; i<mac.length; i++) {
            byte b=mac[i];
            int value=0;
            if (b>=0&&b<=16) {
                value=b;
                sb.append("0"+Integer.toHexString(value));
            } else if (b>16) {
                value=b;
                sb.append(Integer.toHexString(value));
            } else {
                value=256+b;
                sb.append(Integer.toHexString(value));
            }
            if (i!=mac.length-1) {
                sb.append(":");
            }
        }
        return sb.toString();
    }

//    无线的:
    private static String getWifiMacAddr(Context context, String macAddr) {
        WifiManager wifi=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info=wifi.getConnectionInfo();
        if (null!=info) {
            String addr=info.getMacAddress();
            if (null!=addr) {
                macAddr=addr;
            }
        }
        return macAddr;
    }



    public static int getVersionCode() {
        PackageManager manager = RunTimeApplication.getCurApp().getPackageManager();
        int code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(RunTimeApplication.getCurApp().getPackageName(), 0);
            code = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }

    public static String getVersionName() {
        PackageManager manager = RunTimeApplication.getCurApp().getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(RunTimeApplication.getCurApp().getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

}
